package com.lzx.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class WeatherUtil {
    public Map<String,Object> getTodayWeather(String city_code, String city_name, String date) {
        //参数url化
//        String city = null;
//        try {
//            city = java.net.URLEncoder.encode(city_code, "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        //拼地址   101051203
        //String apiUrl = String.format("https://www.sojson.com/open/api/weather/json.shtml?city=%s",city);
        String apiUrl = String.format("http://t.weather.sojson.com/api/weather/city/" + city_code);
        //开始请求
        URL url = null;
        try {
            url = new URL(apiUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection open = null;
        try {
            open = url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream input = null;
        try {
            input = open.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }


        //这里转换为String，带上包名，怕你们引错包
        String result = null;
        try {
            result = org.apache.commons.io.IOUtils.toString(input,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        //转json对象
        JSONObject jsonObject = JSONObject.fromObject(result);
        //接着转
        JSONObject data = JSONObject.fromObject(jsonObject.getString("data"));
        //转jsonArray
        JSONArray jsonArray = JSONArray.fromObject(data.getString("forecast"));
        JSONObject weatherinfo = JSONObject.fromObject(jsonArray.getString(0));
        //当天天气
        //map.put("tianqi_chengshi",jsonObject.getString("city"));//城市
        map.put("tianqi_chengshi",city_name);//城市
        map.put("tianqi_wendu",data.getString("wendu"));//温度
        map.put("tianqi_zuigaowendu",weatherinfo.getString("high").substring(3));//高温
        map.put("tianqi_zuidiwendu",weatherinfo.getString("low").substring(3));//低温
        map.put("tianqi_riqi",weatherinfo.getString("week"));//星期
        map.put("tianqi_createTime",date);//星期
        map.put("tianqi_fengxiang",weatherinfo.getString("fx"));//风向
        map.put("tianqi_fengsu",weatherinfo.getString("fl"));//风速
        map.put("tianqi_tianqi",weatherinfo.getString("type"));//天气
        map.put("tianqi_zhuyixinxi",weatherinfo.getString("notice"));//注意信息

        return map;
    }
}
